package dao

import (
	"errors"

	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
)


func OpenDbWithDsn(diverName, dsn string) (*gorm.DB, error) {
	if diverName == "mysql" {
		return OpenMysqlDbWithDsn(dsn)
	}
	return nil, errors.New("not support db type=" + diverName)
}

//使用dsn进行连接
func OpenMysqlDbWithDsn(dsn string) (*gorm.DB, error) {
	//使用dsn进行连接
	
	return gorm.Open(mysql.New(mysql.Config{
		DSN: dsn,
		DefaultStringSize: 171,
		SkipInitializeWithVersion: false,
	}), &gorm.Config{
		SkipDefaultTransaction: false, //gorm在做写操作（创建、更新、删除）会以事务的形式去做，如果没有需求可以关闭
		//命名策略
		NamingStrategy:  schema.NamingStrategy{
			TablePrefix: "gg_",   // 表的前缀
			SingularTable: false, // 表名是否用负数形式表名
		},
		//跳过gorm自动建立物理外键的过程，物理外键会导致很多问题
		DisableForeignKeyConstraintWhenMigrating: true,
	})
}

func CreateTable(db *gorm.DB, model interface{}) error {
	return db.Set("gorm:table_options", "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci").AutoMigrate(model)
}